<template>
   <div class="red-book-form">
        <a-form layout="vertical" >
          <a-form-item label="标题"  v-bind="validateInfos.title">
            <a-input v-model:value="formRef.title" placeholder="请输入标题" />
          </a-form-item>  
          <a-form-item label="封面"  v-bind="validateInfos.cover_img" >
         
            <a-upload
                    :action="$utils.imgAction"
                    :headers="{ 'org-token': $store.getters.token }"
                    v-model:file-list="imgInfoList"
                    @change="handleLogoUpload"
                    @preview="handlePreview"
                    :multiple="imgMinNum>1"
                    name="image"
                    :data="{ dir: 'work_ai' }"
                    accept="image/*"
                    list-type="picture-card"
                  >
                    <div v-if="!formRef.cover_img.length||formRef.cover_img.length<imgMaxNum">
                      <PlusOutlined />
                      <div>上传封面</div>
                    </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="话题">
                <a-select
                v-model:value="selectTopicList"
              
                show-search
                @search="handleSearch"
               :filter-option="false"
                @change="handleChange"
                mode="multiple"
                :maxTagCount="20"
                placeholder="请选择话题"
              
               
              >
              <a-select-option   :disabled="selectTopicList.length>19&&!selectTopicList.includes(item.key)" :value="item.key" v-for="(item,index) in topicList" :key="item.key">{{ item.name }}</a-select-option>
            </a-select>
            <div class="mt-5 text-gray-6">您可以添加20个话题</div>
          </a-form-item>
          <a-form-item label="权限设置" required>
            <a-radio-group v-model:value="formRef.is_private">
              <a-radio :value="0">公开（所有人可见）</a-radio>
              <a-radio :value="1">私密（仅自己可见）</a-radio>
           </a-radio-group>
          </a-form-item>
          <a-form-item label="发布时间" required>
            <a-radio-group v-model:value="formRef.publishType">
              <a-radio :value="1">立即发布</a-radio>
              <a-radio :value="2">定时发布</a-radio>
           </a-radio-group>
          </a-form-item>
          <a-form-item  v-if="formRef.publishType==2"  v-bind="validateInfos.fix_at">
              <a-date-picker :disabledDate="disabledDate"  :disabled-time="disabledDateTime" :show-time="{ format:'YYYY-MM-DD HH:mm' }" format="YYYY-MM-DD HH:mm" placeholder="请选择时间" @change="onTimeChange" />
          </a-form-item>
        </a-form>
        <a-modal :visible="previewVisible" :footer="null" @cancel="()=>previewVisible=false">
         <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
   </div> 
</template>
  
  <script>
  import {
    defineComponent,
    reactive,
    toRefs,
    computed,
    watchPostEffect,
    ref,
  } from "vue";
  import { useVModel } from '@vueuse/core'
  import request from "../../../common/utils/request"
  import utils from "@/common/utils/utils"
  import { useRoute, useRouter } from "vue-router";
  import moment from 'moment'
  import { Modal, notification, message,Form } from "ant-design-vue";
  import { CloseOutlined, SyncOutlined,PlusOutlined } from "@ant-design/icons-vue";
  import _ from  'lodash'
 
  import { useDebounceFn } from '@vueuse/core'
import { watch } from "vue";
import { nextTick } from "vue";
  let qrCodeTimer = null;
  export default defineComponent({
    name: "xiaohongshu",
    components: { CloseOutlined, SyncOutlined,PlusOutlined },
    formData: {
      title: '',
      cover_img: [],
      is_private:0,
      publishType:1,
      fix_at:null,
      hash_tag:[],
    },
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
      formData:{
        type: Object,
        default: ()=>null
      },
      title:{
        type: String,
        default: '',
      },
      accountId:{
        type:[Number,String],
        default:''
      },
      content:{
        type: String,
        default: '',
      },
      group_account_list:{
        type: Array,
        default: ()=>[]
      },
    },
    
    setup(props, context) {
      const state = reactive({
        previewImage:'',
        previewVisible:false,
        publishTime:'',
      
        topicList:[],
        selectTopicList:[],
        totalTopicList:[],
        isRequired:false,
      });
      
      const formRef = useVModel(props, 'formData', context.emit)

      const useForm = Form.useForm;
      
     
      let  imgInfoList = ref([])
      let validate_cover_img = async(_rule, value)=>{
        if(imgMinNum.value>0&&imgInfoList.value.length==0){
          return Promise.reject('请上传封面');
        }else{
          return Promise.resolve();
        }
     }
     let validate_time = ()=>{
     
        if(formRef.value.publishType==2&&!formRef.value.fix_at){
         
          return Promise.reject('请选择发布时间');
        }else{
          return Promise.resolve();
        }
     }
     let validate_title = () => {

        if (formRef.value.title.length == 0) {
          return Promise.reject('请填写标题');
        }
        if (conentTxt.value.length>1000) {
          console.log(conentTxt.value.length);
          return Promise.reject('小红书文章字数不能大于1000');
        }
        return Promise.resolve();
      }
    
      const onTimeChange = (e)=>{
       
        formRef.value.fix_at = e?moment(e).format('YYYY-MM-DD HH:mm'):null
      }
      
        const handleLogoUpload = (info)=>{
       
          let resFileList = [...info.fileList];
        if (resFileList.length) {
          resFileList.map((file, index) => {
            if (file.response) {
              if (file.response.code == 1000) {
                file.url = file.response.data.fileUrl;
              } else {
                message.warning(file.response.msg);
                resFileList.splice(index, 1);
              }
            }
          });
        }
        
        imgInfoList.value = resFileList;
        formRef.value.cover_img = resFileList.map(item=>{
          return item.url
        })
      
       
        }
     
      //   const getAccountList = async () => {
      //   const { result } = await request.get("/work_ai", "/org/platform/account/group/list", {})
      //   props.group_account_list = result
      // }
      // 获取话题列表
      
      const getTopicList = async (keyword='') => {
        const { result } = await request.post("/work_ai", "/org/platform/account/topic", {id:props.accountId,keyword})
        state.topicList = result
        state.totalTopicList.push(...state.topicList)
        state.totalTopicList = _.uniqBy(state.totalTopicList, 'key')
        
      }
      
      // getAccountList()
      getTopicList()
      const imgMaxNum = computed(()=>{
        return props.group_account_list.find(item=>item.key=='xiaohongshu')?.max_upload_number || 0
       
      })
      const imgMinNum = computed(()=>{
        return props.group_account_list.find(item=>item.key=='xiaohongshu')?.min_upload_number || 0
        
       
      })
      const handleChange = (e)=>{
        
        if(e.length){
          formRef.value.hash_tag =  state.totalTopicList.filter(item=>e.includes(item.key))
        }
        if(e&&e.length>19){
           message.warning('最多选择20个话题')
        }
      }
      const debouncedFn = useDebounceFn((e) => {
        getTopicList(e)
        }, 500)
        
      const handleSearch = (keyword)=>{
        debouncedFn(keyword)
      }
     
       
      watch(() => formRef.value.publishType, (val) => {
        if (val ==2 ) {
          validate(['fix_at'])
        }
      })
      const rulesRef = reactive({
      title: [
          { required: true,validator:validate_title, },
        ],
        cover_img:[
          {
            required:imgMinNum.value>0,
            validator: validate_cover_img,
            trigger: 'change',
          }
        ],
        fix_at:[
          {
            required:true,
            validator: validate_time,
            trigger: 'change',
          }
        ],
     })
    
     const { resetFields ,validate,validateInfos } = useForm(formRef, rulesRef)
     watch(()=>props.title,(newTitle,oldTitle)=>{
        if(! formRef.value.title || formRef.value.title == oldTitle){
          formRef.value.title = props.title
        }
        },
        {immediate:true})
        watch(() => imgMinNum.value, (val) => {

        if (val > 0) {
          validateInfos.cover_img.required = true
         
        }
      })
      const disabledDate= (current)=>{
        // 时间组件当前日期之前的日期不能选择
        return current && current < moment().startOf('day')
      }
      const disabledDateTime = (choosTime) => {
      let currentHour = moment().hour()
      let currentMinute = moment().minute()
    
      let disabledMinutes =  () => []
      let disabledHours = ()=>[]
      if(choosTime){
        disabledMinutes = moment(choosTime)>moment()?
       () => []:
       () => Array.from({ length: 61 }, (_, index) => index).splice(0, currentMinute + 1)

       disabledHours = moment(choosTime)>moment()?() => []:
       () => Array.from({ length: 25 }, (_, index) => index).splice(0, currentHour)
      }

      return {
        disabledHours,
        disabledMinutes,

      };
    }
      const handlePreview = async (file )=>{
          if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
        state.previewImage = file.url || file.preview;
        state.previewVisible = true;
      }
      const getBase64 = (file)=>{
        return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
  });
      }
      const conentTxt = computed(()=>{
        let pureText = props.content.replace(/(<([^>]+)>)/gi, '');
        return pureText
      })

      watch(()=>props.content,()=>{
       
      let {images}  = utils.parseRichText(props.content)
   
      if( formRef.value.cover_img.length==0){
          formRef.value.cover_img = images.slice(0,imgMaxNum.value)
          console.log(formRef.value.cover_img,imgMaxNum.value);
          imgInfoList.value = images.slice(0,imgMaxNum.value).map((item,index)=>{
          return {
            uid: index,
            name: 'image.png',
            status: 'done',
            url: item,
          }
        })
        
      }
   
   },{deep:true,immediate:true})
      return {
        ...toRefs(state),
        onTimeChange,
        formRef,
        handleLogoUpload,
        imgInfoList,
        imgMaxNum,
        imgMinNum,
        handleChange,
        handleSearch,
        rulesRef,
        validate,
        validateInfos,
        disabledDate,
        disabledDateTime,
        handlePreview,
      
      };
    },
  });
  </script>
  
  <style lang="less" scoped>
  :deep(.ss-row){
    flex-wrap: unset;
  }
  :deep(.ss-form-item-has-error .ss-upload){
    background-color: #fff;
    border-color: #ff4d4f;
  }                        
  </style>
  